angular.module('product.controllers', [])

//默认分类管理
.controller('DefaultProductCatalogsCtrl', function($scope,$state) {
	var defaultCatalogsSubHandle = $scope.subscribe('default_options');
	$scope.helpers({
		buildinCatalogs: function() {
			return DefaultOptions.findOne({name:'默认分类'});
		}
	});
	$scope.cataTree=[];
	$scope.cataTreeLoaded=false;
	$scope.autorun(function(){
		if(defaultCatalogsSubHandle.ready() && $scope.buildinCatalogs){
			var createTree = function(pId){
				var arr = [];
				var cursor = [];
				$scope.buildinCatalogs.value_set.forEach(function (cat) {
					if(cat.parent_id == pId){
						cursor.push(cat);
			    	}
			    });
				cursor.forEach(function (cat) {
					if(cat.cid){
						cat.children = createTree(cat.cid);
			    	}
			    	arr.push(cat);
			    });
			    return arr;
			};
		    $scope.cataTree = createTree();
		    $scope.cataTreeLoaded=true;
		}
	});


	//选中分类的数量
	$scope.selectedCount=0;
	$scope.select=function($item){
		//处理父分类链
		var checkParents = function(item){
			var parent=null;
			$scope.buildinCatalogs.value_set.indexOf();
			$scope.buildinCatalogs.value_set.forEach(function(cat){
				if(cat.cid == item.parent_id){
					parent = cat;
					return;
				}
			});
			if(item.isChecked){
				if(!parent.isChecked){
					parent.isChecked=true;
					$scope.selectedCount++;
				}
				if(parent.parent_id){
					checkParents(parent);
				}
			}else{
				var handle = true;
				parent.children.forEach(function(child){
					if(child.isChecked){
						handle = false;
						return;
					}
				});

				if(handle){
					parent.isChecked=false;
					$scope.selectedCount--;
					if(parent.parent_id){
						checkParents(parent);
					}
				}
			}
		};
		//处理子分类链
		var checkChilren = function(item){
			var handle = true;
			item.children.forEach(function(child){
				if(item.isChecked){
					if(child.isChecked){
						handle = false;
						return;
					}
				}else{
					if(!child.isChecked){
						handle = false;
						return;
					}
				}
			});
			if(handle){
				item.children.forEach(function(child){
					child.isChecked=item.isChecked;
					$scope.selectedCount++;
					if(child.children.length){
						checkChilren(child);
					}

				});
			}
		};
		if($item.isChecked){
			$scope.selectedCount++;
		}else{
			$scope.selectedCount--;
		}
		if($item.parent_id){
			checkParents($item);
		}
		if($item.children.length){
			checkChilren($item);
		}
	};

	$scope.importCat = function(){
		var selectedItems=[];
		var getSelectedCat = function(catObject){
			catObject.forEach(function(cat){
				if(cat.isChecked){
					selectedItems.push(angular.copy(cat));
				}
				if(cat.children && cat.children.length){
					getSelectedCat(cat.children);
				}
			});
		};
		var unCheckAll = function(cats){
			cats.forEach(function(cat){
				if(cat.isChecked){
					cat.isChecked=false;
				}
				if(cat.children && cat.children.length){
					unCheckAll(cat.children);
				}
			});
		};
		getSelectedCat($scope.cataTree);
		selectedItems.forEach(function(item){

			item.children=undefined;
			item.isChecked=undefined;
			item.fromDefault=true;
		});

		Meteor.call('importProductCata', selectedItems, function(error){
          if (error) {
            console.log(error);
          }else {
          	//重置选择项
          	unCheckAll($scope.cataTree);
          	$state.go('app.product-catalogs');
          }
        });
	};
})

//分类管理
.controller('ProductCatalogsCtrl', function($scope,$ionicModal) {
	$scope.listCanSwipe = true;
	var productCatalogsSubHandle = $scope.subscribe('product_catalogs');
	$scope.helpers({
		catalogs: function() {
			return ProductCatalogs.find({});
		}
	});
	$scope.myCataTree=[];
	$scope.autorun(function(){
		if(productCatalogsSubHandle.ready() && $scope.catalogs){
			var createTree = function(pId,pId2){
				var cursor = ProductCatalogs.find({'$or':[{"parent_id": pId},{"parent_id":pId2}]});
				var arr = [];
				cursor.forEach(function (obj) {
					if(obj.fromDefault && obj.cid){
						obj.children = createTree(obj.cid,obj._id);
			    	}else{
			    		obj.children = createTree(obj._id,obj._id);
			    	}
			    	arr.push(obj);
			    });

			    return arr;
			};
		    $scope.myCataTree = createTree();
		}
	});

	$ionicModal.fromTemplateUrl('templates/product/add-catalog.html', {
		scope: $scope,
		animation: 'slide-in-up',
		focusFirstInput: true
	}).then(function(modal) {
		$scope.modal = modal;
	});
	$scope.openModal = function() {
		$scope.modal.show();
	};
	$scope.closeModal = function() {
		$scope.modal.hide();
	};
	$scope.$on('$destroy', function() {
		$scope.modal.remove();
	});
	$scope.$on('modal.hidden', function() {
	});
	$scope.$on('modal.removed', function() {
	});
	//添加分类
	$scope.newCatalog = {};
	$scope.add = function(){
		if (!$scope.newCatalog.name) return;
		Meteor.call('addProductCata', $scope.newCatalog, function(error){
          if (error) {
            console.log(error);
          }
          else {
            $scope.closeModal();
          }
        });
	};
})

.controller('ProductCatalogDetailCtrl',function($scope,$stateParams,$ionicModal,$ionicPopup,$state){
	$scope.listCanSwipe = true;
	var productCatalogsSubHandle = $scope.subscribe('product_catalogs');
	$scope.helpers({
		catalogs: function() {
			return ProductCatalogs.find();
		},
		catalog: function() {
			return ProductCatalogs.findOne({_id:$stateParams._id});
		}
	});
	$scope.autorun(function(){
		if(productCatalogsSubHandle.ready() && $scope.catalog){
			var parent = ProductCatalogs.findOne({"$or":[{_id:$scope.catalog.parent_id}, {cid:$scope.catalog.parent_id}]});
			$scope.parentName = parent?parent.name:'无';
		}
	});
	//更新分类
	$scope.update = function(){
		var theCatalog = {
			_id:$scope.catalog._id,
			name:$scope.catalog.name,
			company_id:$scope.catalog.company_id,
			parent_id:$scope.catalog.parent_id
		};
		Meteor.call('updateProductCata', theCatalog, function(error){
          if (error) {
            console.log(error);
          }
          else {
          }
        });
	};
	// 删除分类
	$scope.delete = function(index) {
		var confirmPopup = $ionicPopup.confirm({
			title: '删除分类',
			template: '确定要删除 “<span class="royal">'+$scope.catalog.name+'</span>” 分类?<br/><br/>删除后，该分类下商品将移至 “默认分类”',
			cancelText: '取消',
			okText: '确定',
			okType: 'button-royal',
		});

		confirmPopup.then(function(res) {
			if(res) {
				Meteor.call('deleteProductCata', $scope.catalog._id, function(error){
		          if (error) {
		            console.log(error);
		          }
		          else {
		          }
		        });
				$state.go('app.product-catalogs');
			}
	   });
	};
	// 属性
	$ionicModal.fromTemplateUrl('templates/product/properties.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.modal = modal;
	});
	$scope.openModal = function(property) {
		if(property.value_set && property.value_set.length){
			property.value_set.forEach(function (value) {
				value.enabled = (value.enabled===undefined || value.enabled===true)? true:false;
			});
			$scope.property = property;
			$scope.modal.show();
		}
	};
	$scope.closeModal = function() {
		$scope.modal.hide();
	};
	$scope.$on('$destroy', function() {
		$scope.modal.remove();
	});
	$scope.$on('modal.hidden', function() {
	});
	$scope.$on('modal.removed', function() {
	});
	// 更新分类商品的属性
	$scope.updateProperty = function(property){
		var data = {
			'catalogId' : $scope.catalog._id,
			'_id':property._id,
			'value_set' : property.value_set
		};
		data.value_set.forEach(function(v){
        	v.$$hashKey=undefined;
        });

		Meteor.call('updateProductProperty', data, function(error){
          if (error) {
            console.log(error);
          }
          else {
            $scope.closeModal();
          }
        });
	};
})

.controller('ProductsCtrl',function($scope,$ionicPopup,PopupService){
	$scope.showDelete=false;
	$scope.toggleDelete = function(){
		$scope.showDelete=! $scope.showDelete;
	};
	$scope.showCat=false;
	$scope.toggleCat=function(){
		$scope.showCat = ! $scope.showCat;
	};

	var productsSubHandle = $scope.subscribe('products');
	var productCatalogsSubHandle = $scope.subscribe('product_catalogs');
	$scope.helpers({
		catalogs: function() {
			return ProductCatalogs.find({});
		},
		products: function() {
			return Products.find({});
		}
	});

	$scope.autorun(function(){
		if(productsSubHandle.ready() && $scope.products){
			$scope.title = '全部商品';
			// 获取品牌列表,key为品牌名，value为该品牌商品数量
			$scope.brandList = {};
			$scope.products.forEach(function(product) {
				var brandName = product.properties.brand.value;
				if(!$scope.brandList[brandName]){
					$scope.brandList[brandName]=1;
				}else{
					$scope.brandList[brandName] = $scope.brandList[brandName]>99?"99+":$scope.brandList[brandName]+1;
				}
			});
		}
	});

 	$scope.delete = function(productId){
		var myPopup = $ionicPopup.show({
			template: '<p class="assertive">确认要删除该商品吗？<p>',
			title: '删除商品',
			scope: $scope,
			buttons: [
				{ text: '取消' },
				{ text: '<b>确定</b>',type: 'button-royal',
				onTap: function(e) {
					Meteor.call('deleteProduct', productId, function(error){
						if (error) {
							PopupService.showAlert(error.reason);
							console.log(error);
						}	else {
							ToastService.show('状态更新成功');
						}
			    });
				}
			}]
		});
	};
})
//添加商品
.controller('AddProductCtrl', function ($scope,$state,$ionicModal,$cordovaBarcodeScanner,PopupService) {

	var productsSubHandle = $scope.subscribe('products');
	var productCatalogsSubHandle = $scope.subscribe('product_catalogs');
	$scope.helpers({
		catalogs: function() {
			return ProductCatalogs.find({});
		},
		products: function() {
			return Products.find({});
		}
	});
	$scope.newProduct={};
	// 选择分类后获取该分类的商品属性
	$scope.getCatalogProperty = function(){
		$scope.catalogs.forEach(function(cata){
			if(cata._id == $scope.newProduct.catalogId && cata.name=="手机"){
				$scope.properties = JSON.stringify(cata.properties);
  			$scope.properties = JSON.parse($scope.properties);
  			$scope.newProduct.catalog = cata.name;
			}
		});
	};
	$scope.scanBarcode = function() {
		$cordovaBarcodeScanner.scan().then(function(imageData) {
			$scope.newProduct.barcode = imageData.text;
			console.log("Barcode Format -> " + imageData.format);
			console.log("Cancelled -> " + imageData.cancelled);
		}, function(error) {
			PopupService.showAlert(error);
			console.log("An error happened -> " + error);
		});
	};
	// 属性
	$ionicModal.fromTemplateUrl('templates/product/select-property.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.modal = modal;
	});
	// 传递 点击的属性的索引，和可选属性值
	$scope.openModal = function(index,property) {
		$scope.property = property;
		$scope.property.index = index;
		$scope.modal.show();
	};
	$scope.closeModal = function() {
		$scope.modal.hide();
	};
	$scope.$on('$destroy', function() {
		$scope.modal.remove();
	});
	$scope.$on('modal.hidden', function() {
	});
	$scope.$on('modal.removed', function() {
	});
	$scope.selectProperty=function(index,selectedValue){
		$scope.newProduct.properties[index].value = selectedValue;
		setTimeout(function () {
			$scope.modal.hide();
		}, 500);

	};
	$scope.add = function(){
		$scope.newProduct.catalogId = undefined;
		$scope.newProduct.thumb = 'img/2.jpg';
		Meteor.call('addProduct', $scope.newProduct, function(error){
			if (error) {
				PopupService.showAlert(error.reason);
				console.log(error);
			} else {
				ToastService.show('添加成功');
				$state.go('app.products');
			}
		});
	};
})
.controller('ProductDetailCtrl', function ($scope,$stateParams) {
	var productsSubHandle = $scope.subscribe('products');
	// var productCatalogsSubHandle = $scope.subscribe('product_catalogs');

	$scope.helpers({
		product: function() {
			return Products.findOne({_id:$stateParams._id});
		}
	});
	$scope.update = function(){
		console.log($scope.product);
		Meteor.call('updateProduct', $scope.product, function(error){
			if (error) {
				console.log(error);
			} else {
			}
		});
	};
});
